Crate peekread[][src]

Expand description

This crate allows you to take an arbitrary Read stream and ‘peek ahead’ into the stream without consuming the original stream.

This is done through the PeekRead trait which has the method peek. When this method is called it returns a new PeekCursor object implementing Read, BufRead and Seek that allows you to read from the stream without affecting the original stream.

The PeekRead trait is directly implemented on a select few types, but for most you will have to wrap your type in a SeekPeekReader or BufPeekReader that implements the peeking behavior using respectively seeking or buffering.

Examples

One could try various different parsers on the same stream until one succeeds:

let mut f = SeekPeekReader::new(File::open("ambiguous")?);

// HTML is so permissive its parser never fails, so check for signature.
if f.starts_with("<!DOCTYPE html>\n") {
    Ok(ParseResult::Html(parse_as_html(f)))
} else {
    // Can pass PeekCursor to functions accepting T: Read without them
    // having to be aware of peekread.
    parse_as_jpg(f.peek()).map(ParseResult::Jpg)
       .or_else(|_| parse_as_png(f.peek()).map(ParseResult::Png))
       .or_else(|_| parse_as_gif(f.peek()).map(ParseResult::Gif))
       .or_else(|_| parse_as_javascript(f.peek()).map(ParseResult::Js))
}

Modules

Details for those wishing to implement PeekRead.

Structs

A wrapper for a Read stream that implements PeekRead using a buffer to store peeked data.

An object implementing BufRead and Seek to peek ahead in a stream without affecting the original stream.

A wrapper for a Read + Seek stream that implements PeekRead using seeking.

Traits

A trait for a Read stream that supports peeking ahead in the stream.